package com.mundus.engine.resources;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import org.lwjgl.util.glu.GLU;

import com.mundus.engine.assets.Log;

public class ShaderLoader {
	private static String[] _attributes;
	
	public static Shader getShader(String vertexShader, String fragmentShader, String... attributes) throws IOException{
		Shader shader = new Shader();
		_attributes = attributes;
		shader._sId = createShader(vertexShader, fragmentShader);
		return shader;
	}
	
	private static int createShader(String vs_path, String fs_path) throws IOException{
		int errorCheckValue = GL11.glGetError();
		
		int vsId = loadShaderFile(vs_path,GL20.GL_VERTEX_SHADER);
		int fsId = loadShaderFile(fs_path,GL20.GL_FRAGMENT_SHADER);
		
		int pId = GL20.glCreateProgram();
		GL20.glAttachShader(pId, vsId);
		GL20.glAttachShader(pId, fsId);
		
		for(int i = 0; i < _attributes.length; i++)
			GL20.glBindAttribLocation(pId,i,  _attributes[i]);
		
		GL20.glLinkProgram(pId);
		GL20.glValidateProgram(pId);
		
		errorCheckValue = GL11.glGetError();
		if (errorCheckValue != GL11.GL_NO_ERROR) {
			Log.error("ERROR - Could not create the shaders:" + GLU.gluErrorString(errorCheckValue));
			System.exit(-1);
		}
		
		return pId;
	}
	
	private static int loadShaderFile(String filename, int type) throws IOException{
		StringBuilder shaderSource = new StringBuilder();
		
		int shaderID = 0;		    
	    String path = Resource.getResourcePath() + "\\" + filename;
		BufferedReader reader = new BufferedReader(new FileReader(path));
		String line;
		while ((line = reader.readLine()) != null) {
			shaderSource.append(line).append("\n");
		}
		reader.close();
		
		shaderID = GL20.glCreateShader(type);
		GL20.glShaderSource(shaderID, shaderSource);
		GL20.glCompileShader(shaderID);
		
		return shaderID;
	}
}
